﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using WCell.Constants;
using WCell.Constants.NPCs;
using WCell.Core;
using WCell.Util.Threading;
using WCell.RealmServer.Guilds;
using WCell.RealmServer.Chat;
using WCell.RealmServer.Entities;
using WCell.RealmServer.Handlers;
using WCell.Util;
using WCell.Util.NLog;

namespace Kingdoms
{
    public static class KingdomGuildMgr
    {
        public static Dictionary<uint, GuildExtension> Guilds = new Dictionary<uint, GuildExtension>();

        public static void Init()
        {
            /*
            try
            {
                GuildExtension.Exists();
            }
            catch
            {
                //DatabaseUtil.CreateSchema();
            }
            */

            GuildExtension[] _guilds = null;
            _guilds = GuildExtension.FindAll();

            foreach (GuildExtension guilds in _guilds)
            {
                Guilds.Add(guilds.Id, guilds);
            }
            
        }

        static public void AddGuild(Guild guild)
        {
            GuildExtension newguild = new GuildExtension();
            
            newguild.Id = guild.Id;
            newguild.GuildPoints = 0;

            Guilds.Add(newguild.Id, newguild);
        }

        public static void SaveIntoDB()
        {
            foreach (GuildExtension guild in Guilds.Values)
            {
                guild.Save();
            }
        }

        public static void OnDisband(Guild guild) // needs to be hooked up to a guild disband event.
        {
            var id = guild.Id;
            if (Guilds.ContainsKey(id))
            {
                var g = Guilds[id];

                foreach (Territory t in g.OwnedTerritories)
                {
                    t.Reset();
                }
                Guilds.Remove(id);
                g.Delete();
            }
            else return;
        }
    }
}
